package net.skyplabs.android.tvrc;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class tvrcActivity extends Activity implements OnTouchListener
{
	private static final long repeatTime = 300;
	
    private long lastTime = 0;
    private boolean connected = false;
    private boolean isFirstTime = true;
    
    private BluetoothAdapter mBluetoothAdapter = null;
    private BtInterface bt = null;
    
    private WakeLock wakeLock = null;
    private PowerManager powerManager = null;
    
    private Button on, off;
    private Button volPlus, volMinus;
    private Button ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8, ch9, ch0, chPlus, chMinus;
    private Button tvdtv, ext1, ext2, hdmi1, hdmi2, hdmi3, pc;
    private Button dvdIn, menu, enter;
    private ImageButton mute, dvdOnOff, eject, up, down, left, right;
    private ImageButton play, pause, stop, fastForward, fastRewind, nextChapter, previousChapter;
    
    private TextView logview;
    private View buttonPressed;
    
    private Handler mHandler;
    
    final Handler handlerMessage = new Handler()
    {
        public void handleMessage(Message msg)
        {
            String data = msg.getData().getString("receivedData");
            long t = System.currentTimeMillis();
            
            if (t-lastTime > 100)
            { // Pour éviter que les messages soit coupés
                logview.setText("");
				lastTime = System.currentTimeMillis();
			}
            
            logview.append(data);
        }
    };
    
    final Handler handlerStatus = new Handler()
    {
        public void handleMessage(Message msg)
        {
            int co = msg.arg1;
            
            if (co == 1)
            {
            	logview.setText(getString(R.string.connected));
            	connected = true;
            }
            else if (co == 2)
            {
            	logview.setText(getString(R.string.no_paired));
            	connected = false;
            }
        }
    };
    
    Runnable cmdAction = new Runnable()
    {
    	@Override
    	public void run()
    	{
    		if (buttonPressed == on)
				bt.sendData("007007153");
			else if(buttonPressed == off)
				bt.sendData("007007152");
			else if(buttonPressed == mute)
				bt.sendData("007007015");
			else if(buttonPressed == volPlus)
				bt.sendData("007007007");
			else if(buttonPressed == volMinus)
				bt.sendData("007007011");
			else if(buttonPressed == ch1)
				bt.sendData("007007004");
			else if(buttonPressed == ch2)
				bt.sendData("007007005");
			else if(buttonPressed == ch3)
				bt.sendData("007007006");
			else if(buttonPressed == ch4)
				bt.sendData("007007008");
			else if(buttonPressed == ch5)
				bt.sendData("007007009");
			else if(buttonPressed == ch6)
				bt.sendData("007007010");
			else if(buttonPressed == ch7)
				bt.sendData("007007012");
			else if(buttonPressed == ch8)
				bt.sendData("007007013");
			else if(buttonPressed == ch9)
				bt.sendData("007007014");
			else if(buttonPressed == ch0)
				bt.sendData("007007017");
			else if(buttonPressed == chPlus)
				bt.sendData("007007018");
			else if(buttonPressed == chMinus)
				bt.sendData("007007016");
			else if(buttonPressed == tvdtv)
				bt.sendData("007007067");
			else if(buttonPressed == ext1)
				bt.sendData("007007132");
			else if(buttonPressed == ext2)
				bt.sendData("007007235");
			else if(buttonPressed == hdmi1)
				bt.sendData("007007233");
			else if(buttonPressed == hdmi2)
				bt.sendData("007007190");
			else if(buttonPressed == hdmi3)
				bt.sendData("007007194");
			else if(buttonPressed == pc)
				bt.sendData("007007105");
			else if(buttonPressed == dvdOnOff)
				bt.sendData("067083001");
			else if(buttonPressed == eject)
				bt.sendData("067083048");
			else if(buttonPressed == dvdIn)
				bt.sendData("067083017");
			else if(buttonPressed == menu)
				bt.sendData("067083054");
			else if(buttonPressed == up)
				bt.sendData("067083013");
			else if(buttonPressed == down)
				bt.sendData("067083021");
			else if(buttonPressed == left)
				bt.sendData("067083037");
			else if(buttonPressed == right)
				bt.sendData("067083029");
			else if(buttonPressed == enter)
				bt.sendData("067083005");
			else if(buttonPressed == play)
				bt.sendData("067083003");
			else if(buttonPressed == stop)
				bt.sendData("067083011");
			else if(buttonPressed == pause)
				bt.sendData("067083125");
			else if(buttonPressed == fastForward)
				bt.sendData("067083117");
			else if(buttonPressed == fastRewind)
				bt.sendData("067083116");
			else if(buttonPressed == previousChapter)
				bt.sendData("067083027");
			else if(buttonPressed == nextChapter)
				bt.sendData("067083019");
    		
    		mHandler.postDelayed(this, repeatTime);
    	}
    };
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        
        if (mBluetoothAdapter == null)
        {
        	Toast.makeText(this, R.string.no_bluetooth, Toast.LENGTH_LONG).show();
        	finish();
        	return;
        }
        
        powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Mon Lock");
        
        setContentView(R.layout.main);
        bindWidgets();
        logview.setText(getString(R.string.disconnected));
    }
    
    @Override
    public void onStart()
    {
    	super.onStart();
    	
    	if (!mBluetoothAdapter.isEnabled())
    	{
    		mBluetoothAdapter.enable();
    		bt = null;
    		
    		while(mBluetoothAdapter.getState() != BluetoothAdapter.STATE_ON);
    	}
    		
        if (bt == null)
        {
        	bt = new BtInterface(handlerStatus, handlerMessage);
        	bt.connect();
        }
    }
    
    @Override
    public void onResume()
    {
    	super.onResume();
    	
    	wakeLock.acquire();
    }
    
    @Override
    public void onPause()
    {
    	wakeLock.release();
    	
    	super.onPause();
    }
    
    @Override
    public void onStop()
    {
    	if (connected)
    	{
    		bt.close();
    		bt = null;
    		connected = false;
    		logview.setText(getString(R.string.disconnected));
    	}
    	
    	mBluetoothAdapter.disable();
    	super.onStop();
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
    	super.onConfigurationChanged(newConfig);
    	
    	String currentLogview = logview.getText().toString();
    		
    	setContentView(R.layout.main);
    	bindWidgets();
    		
    	logview.setText(currentLogview);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.main, menu);
		    
	    return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
	    menu.clear();
	
	    if (!connected)
	    	menu.add(0, R.menu.main, 0, getString(R.string.connection));
	    else
	    	menu.add(0, R.menu.main, 0, getString(R.string.disconnection));
	
	    return super.onPrepareOptionsMenu(menu);	
    }
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item)
    {    	
	    switch (item.getItemId())
	    {
	
		    case R.menu.main :
		    	if (bt == null)
		    	{
		    		bt = new BtInterface(handlerStatus, handlerMessage);
		        	bt.connect();
		    	}
		    	else if (connected)
		    	{
		    		bt.close();
		    		bt = null;
		    		connected = false;
		    		logview.setText(getString(R.string.disconnected));
		    	}
		    	
		    	return true;
	    }

    	return super.onMenuItemSelected(featureId, item);
    }
    
    private void bindWidgets()
    {
        logview = (TextView)findViewById(R.id.logview);
        logview.setMovementMethod(ScrollingMovementMethod.getInstance());
        
        on = (Button) findViewById(R.id.on);
        on.setOnTouchListener(this);
        
        off = (Button) findViewById(R.id.off);
        off.setOnTouchListener(this);
        
        mute = (ImageButton) findViewById(R.id.mute);
        mute.setOnTouchListener(this);
        
        volPlus = (Button) findViewById(R.id.volPlus);
        volPlus.setOnTouchListener(this);
        
        volMinus = (Button) findViewById(R.id.volMinus);
        volMinus.setOnTouchListener(this);
        
        ch1 = (Button) findViewById(R.id.ch1);
        ch1.setOnTouchListener(this);
        
        ch2 = (Button) findViewById(R.id.ch2);
        ch2.setOnTouchListener(this);
        
        ch2 = (Button) findViewById(R.id.ch2);
        ch2.setOnTouchListener(this);
        
        ch3 = (Button) findViewById(R.id.ch3);
        ch3.setOnTouchListener(this);
        
        ch4 = (Button) findViewById(R.id.ch4);
        ch4.setOnTouchListener(this);
        
        ch5 = (Button) findViewById(R.id.ch5);
        ch5.setOnTouchListener(this);
        
        ch6 = (Button) findViewById(R.id.ch6);
        ch6.setOnTouchListener(this);
        
        ch7 = (Button) findViewById(R.id.ch7);
        ch7.setOnTouchListener(this);
        
        ch8 = (Button) findViewById(R.id.ch8);
        ch8.setOnTouchListener(this);
        
        ch9 = (Button) findViewById(R.id.ch9);
        ch9.setOnTouchListener(this);
        
        ch0 = (Button) findViewById(R.id.ch0);
        ch0.setOnTouchListener(this);
        
        chPlus = (Button) findViewById(R.id.chPlus);
        chPlus.setOnTouchListener(this);
        
        chMinus = (Button) findViewById(R.id.chMinus);
        chMinus.setOnTouchListener(this);
        
        tvdtv = (Button) findViewById(R.id.tvdtv);
        tvdtv.setOnTouchListener(this);
        
        ext1 = (Button) findViewById(R.id.ext1);
        ext1.setOnTouchListener(this);
        
        ext2 = (Button) findViewById(R.id.ext2);
        ext2.setOnTouchListener(this);
        
        hdmi1 = (Button) findViewById(R.id.hdmi1);
        hdmi1.setOnTouchListener(this);
        
        hdmi2 = (Button) findViewById(R.id.hdmi2);
        hdmi2.setOnTouchListener(this);
        
        hdmi3 = (Button) findViewById(R.id.hdmi3);
        hdmi3.setOnTouchListener(this);
        
        pc = (Button) findViewById(R.id.pc);
        pc.setOnTouchListener(this);
        
        dvdOnOff = (ImageButton) findViewById(R.id.dvdOnOff);
        dvdOnOff.setOnTouchListener(this);
        
        eject = (ImageButton) findViewById(R.id.eject);
        eject.setOnTouchListener(this);
        
        up = (ImageButton) findViewById(R.id.up);
        up.setOnTouchListener(this); 
        
        down = (ImageButton) findViewById(R.id.down);
        down.setOnTouchListener(this);
        
        left = (ImageButton) findViewById(R.id.left);
        left.setOnTouchListener(this);
        
        right = (ImageButton) findViewById(R.id.right);
        right.setOnTouchListener(this);
        
        play = (ImageButton) findViewById(R.id.play);
        play.setOnTouchListener(this);
        
        stop = (ImageButton) findViewById(R.id.stop);
        stop.setOnTouchListener(this);
        
        pause = (ImageButton) findViewById(R.id.pause);
        pause.setOnTouchListener(this);
        
        fastForward = (ImageButton) findViewById(R.id.fastForward);
        fastForward.setOnTouchListener(this);
        
        fastRewind = (ImageButton) findViewById(R.id.fastRewind);
        fastRewind.setOnTouchListener(this);
        
        previousChapter = (ImageButton) findViewById(R.id.previousChapter);
        previousChapter.setOnTouchListener(this);
        
        nextChapter = (ImageButton) findViewById(R.id.nextChapter);
        nextChapter.setOnTouchListener(this);
        
        menu = (Button) findViewById(R.id.menu);
        menu.setOnTouchListener(this);
        
        dvdIn = (Button) findViewById(R.id.switchDvdInput);
        dvdIn.setOnTouchListener(this);
        
        enter = (Button) findViewById(R.id.enter);
        enter.setOnTouchListener(this);
    }
    
	public boolean onTouch(View v, MotionEvent event)
	{
		if (connected)
		{
			buttonPressed = v;
			
			switch(event.getAction())
			{
	        	case MotionEvent.ACTION_DOWN:
	        		if (mHandler != null) return true;
	        		mHandler = new Handler();
	        		
	        		if (isFirstTime)
	        		{
	        			isFirstTime = false;
	        			mHandler.post(cmdAction);
	        		}
	        		else
	        			mHandler.postDelayed(cmdAction, repeatTime);
	        		
	        		break;
	        	case MotionEvent.ACTION_UP:
	        		if (mHandler == null) return true;
	        		mHandler.removeCallbacks(cmdAction);
	        		mHandler = null;
	        		isFirstTime = true;
	        		break;
	        }
			
	        return false;
		}
		else
		{
			logview.setText(getString(R.string.no_sent));
			return true;
		}
	}
}